package com.feihong.yw189.paidan.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.bean.IdInfo;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.bean.PaiDanOrder;
import com.feihong.yw189.paidan.dialog.PaiDanShuoMingDialog;
import com.feihong.yw189.paidan.dialog.TuiDanDialog;
import com.feihong.yw189.paidan.inter.AddPhoneNumItemListener;
import com.feihong.yw189.paidan.inter.BeiZhuListener;
import com.feihong.yw189.paidan.inter.RefOrderListListener;
import com.feihong.yw189.paidan.qiangdanservice.LocationSDKTools;
import com.feihong.yw189.paidan.qiangdanservice.LocationUtils;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.feihong.yw189.utils.SelectDataUtils;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.BaseViewHolder;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import me.shaohui.bottomdialog.BottomDialog;


/**
 * 2018/1/24.
 */

public class DispatchListAdapter extends BaseRecyclerAdapter<PaiDanOrder.DataBeanX.OrderItemBean> {

    private Context mContext;
    private Activity mActivity;
    private RefOrderListListener mRefOrderListListener;
    private List<PaiDanOrder.DataBeanX.OrderItemBean> dataList = new ArrayList<>();
    private String buyerMobil = "";

    private PaiDanOrder.DataBeanX.OrderItemBean curentItem = null; // 当前item

    private BottomDialog locationDialog;
    private String order_sn = "";

    private PopupWindow popupWindow;
    private String mCopiedText;
    private String order_type;
    private final MyUsualyDialog dialog;

    public DispatchListAdapter(Context context, RefOrderListListener mRefOrderListListener) {
        super(context, R.layout.card_item_dispatch, new ArrayList<PaiDanOrder.DataBeanX.OrderItemBean>());
        this.mContext = context;
        this.mActivity = (Activity) context;
        this.mRefOrderListListener = mRefOrderListListener;
        initPopupWindow();
        dialog = new MyUsualyDialog(mContext, R.layout.chuli_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        locationDialog = BottomDialog.create(((AppCompatActivity) mContext).getSupportFragmentManager())
                //注意Adapter属于的Activity必须继承AppCompatActivity
                .setViewListener(new BottomDialog.ViewListener() {
                    // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View mapSheetView) {
                        // you can do bind view operation
                        mapSheetView.findViewById(R.id.baidu_btn).setOnClickListener(new locationButtonListener());
                        mapSheetView.findViewById(R.id.gaode_btn).setOnClickListener(new locationButtonListener());
                        mapSheetView.findViewById(R.id.tencent_btn).setOnClickListener(new locationButtonListener());
                        mapSheetView.findViewById(R.id.cancel_btn2).setOnClickListener(new locationButtonListener());
                    }
                })
                .setLayoutRes(R.layout.map_navagation_sheet)
                .setDimAmount(0.1f)
                // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)
                // 点击外部区域是否关闭，默认true
                .setTag("DiTu");
        // 设置DialogFragment的tag
        // .show();
    }

    private void initPopupWindow() {
        View popupView = mActivity.getLayoutInflater().inflate(R.layout.tpl_select_menu, null);

        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity.getResources(), (Bitmap) null));

        TextView select_menu_copy = (TextView) popupView.findViewById(R.id.select_menu_copy);

        select_menu_copy.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText(null, mCopiedText);
            cm.setPrimaryClip(clip);
            Log.e("项目异常", "------mCopiedText------" + mCopiedText);
            ToastUtils.showShortToast(mActivity, "内容已复制到剪切板,快去粘贴吧!");
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        });
    }

    private void setCopyWay(final TextView tv) {

        tv.setOnLongClickListener(v -> {
            mCopiedText = ((TextView) v).getText().toString();
            popupWindow.showAsDropDown(v);
            return false;
        });
    }


    private class locationButtonListener implements View.OnClickListener {


        @Override
        public void onClick(View v) {

            try {
                if (v.getId() == R.id.cancel_btn2) {
                    locationDialog.dismiss();
                    return;
                }
                if (curentItem == null) {
                    Toast.makeText(mContext, "无法满足跳转", Toast.LENGTH_SHORT).show();
                    return;
                }
                LocationUtils locationUtils = new LocationUtils();
                locationUtils.setLatitude(Double.parseDouble(curentItem.getLast_gps_latitude().toString()));
                locationUtils.setLongitude(Double.parseDouble(curentItem.getLast_gps_longitude().toString()));
                if (!TextUtils.isEmpty(curentItem.getLt_address())) {

                    locationUtils.setName(curentItem.getLt_address());

                } else {
                    locationUtils.setName("");
                }
                LocationSDKTools sdkTools = new LocationSDKTools(mContext);

                switch (v.getId()) {
                    case R.id.baidu_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_BAIDU, locationUtils);
                        break;
                    case R.id.gaode_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_GAODE, locationUtils);
                        break;
                    case R.id.tencent_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_TENGXUN, locationUtils);
                        break;
                    default:
                        break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(mContext, "无法启动地图", Toast.LENGTH_SHORT).show();
            }
            locationDialog.dismiss();

        }
    }

    public void setData(List<PaiDanOrder.DataBeanX.OrderItemBean> list) {
        this.dataList = list;
        notifyDataSetChanged();
    }

    @Override
    protected void convert(BaseViewHolder holder, PaiDanOrder.DataBeanX.OrderItemBean item) {
        holder.getView(R.id.tv_order);
        setCopyWay(holder.getView(R.id.tv_order));
        setCopyWay(holder.getView(R.id.tv_name));
        setCopyWay(holder.getView(R.id.tv_sjh));
        setCopyWay(holder.getView(R.id.tv_lxdh));
        setCopyWay(holder.getView(R.id.tv_address));
        setCopyWay(holder.getView(R.id.tv_sfnum));
        setCopyWay(holder.getView(R.id.tv_ltorder));

        int position = holder.getPosition();

        holder.setText(R.id.order_num, position + 1 + ":订单号");


        order_type = item.getOrder_type();
        String order_juli = item.getOrder_juli();

        String status = item.getStatus();
        String address = item.getAddress();
        String remark = item.getRemark();

        // 增加证件号显示
        String user_idcard = item.getUser_idcard();
        if (user_idcard != null && !TextUtils.isEmpty(user_idcard)) {
            holder.getView(R.id.ll_sfnum).setVisibility(View.VISIBLE);
            holder.setText(R.id.tv_sfnum, user_idcard);
        } else {
            holder.getView(R.id.ll_sfnum).setVisibility(View.GONE);
        }
        if ("0425".equals(status)) {
            if (address != null && !TextUtils.isEmpty(address)) {
                if (remark != null && !TextUtils.isEmpty(remark)) {
                    remark = "  备注:" + remark;
                    Log.e("项目异常", "--0425----remark---" + remark);
                    String beizhu = address + remark;
                    SpannableString mp = new SpannableString(beizhu);
                    mp.setSpan(new ForegroundColorSpan(Color.RED), address.length() + 1,
                            beizhu.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);// 字体变色,包前不包后
                    holder.setText(R.id.tv_address, mp);
                } else {
                    holder.setText(R.id.tv_address, address);
                }
            }
        } else {
            if (address != null && !TextUtils.isEmpty(address)) {
                if (remark != null && !TextUtils.isEmpty(remark)) {
                    remark = "  备注:" + remark;
                    String beizhu = address + remark;
                    SpannableString mp = new SpannableString(beizhu);
                    mp.setSpan(new ForegroundColorSpan(Color.RED), address.length() + 1,
                            beizhu.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);// 字体变色,包前不包后
                    holder.setText(R.id.tv_address, mp);
                } else {
                    holder.setText(R.id.tv_address, address);
                }
            }
        }


        // 区分订单来源
//        myHolder.tv_write.setBackgroundResource(R.mipmap.wancheng);
//        myHolder.tv_cancleorder.setBackgroundResource(R.mipmap.pd_td);
        holder.getView(R.id.ll_scdd).setVisibility(View.GONE);
        holder.getView(R.id.ll_blhm).setVisibility(View.GONE);


        if (order_juli != null && !TextUtils.isEmpty(order_juli)) {
            holder.setText(R.id.tv_map, "地图定位" + "\n" + order_juli);
        } else {
            holder.setText(R.id.tv_map, "地图定位");
        }

        String lt_order_sn = item.getLt_order_sn();
        if (lt_order_sn != null && !TextUtils.isEmpty(lt_order_sn)) {
            holder.setText(R.id.tv_ltorder, lt_order_sn);
        }
        order_sn = item.getOrder_sn();
        String user_name = item.getUser_name();
        if (order_sn != null && !TextUtils.isEmpty(order_sn)) {
            holder.setText(R.id.tv_order, order_sn);
        }
        if (user_name != null && !TextUtils.isEmpty(user_name)) {
            holder.setText(R.id.tv_name, user_name);
        }

        String phoneNum = item.getPhonenum();
        buyerMobil = item.getBuyer_mobile();

        if (phoneNum == null || TextUtils.isEmpty(phoneNum)) {
            holder.getView(R.id.ll_blhm).setVisibility(View.GONE);
        } else {
            holder.getView(R.id.ll_blhm).setVisibility(View.VISIBLE);
            holder.setText(R.id.tv_sjh, phoneNum);
        }
        if (buyerMobil != null && !TextUtils.isEmpty(buyerMobil)) {
            holder.setText(R.id.tv_lxdh, buyerMobil);
        }

        String add_time = item.getAdd_time();

        if (add_time != null && !TextUtils.isEmpty(add_time)) {
            holder.setText(R.id.tv_time, add_time);
        }
        String goodsName = item.getGoods_name();

        if (goodsName == null || TextUtils.isEmpty(goodsName)) {
            goodsName = "";
        }
        holder.setText(R.id.tv_endtime, goodsName);

        // 显示订单说明
        holder.setOnClickListener(R.id.tv_endtime, view -> {

            String note1 = item.getNote();// 获取订单说明
            String gdName = item.getGoods_name();// 获取订单说明

            PaiDanShuoMingDialog paiDanShuoMingDialog = new PaiDanShuoMingDialog(mActivity);
            paiDanShuoMingDialog.setContent(gdName, note1);
            paiDanShuoMingDialog.setCanceledOnTouchOutside(false);
            paiDanShuoMingDialog.setCancelable(false);
            paiDanShuoMingDialog.show();
        });

        // 退单
        holder.setOnClickListener(R.id.tv_cancleorder, view -> {

            order_type = item.getOrder_type();

            // 商城订单
            TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "退单", "请输入退单理由", (str, type) -> {

                String orderSn = item.getOrder_sn();
                if (orderSn != null && !TextUtils.isEmpty(orderSn)) {
                    tuiDan(item, orderSn, str, type, order_type);
                } else {
                    ToastUtils.showShortToast(mContext, "订单号为空");
                }
            });
            tuiDanDialog.setCanceledOnTouchOutside(false);
            tuiDanDialog.setCancelable(false);
            tuiDanDialog.show();
        });


        // 转派
        holder.setOnClickListener(R.id.iv_zhuanpai, view -> {

            TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "转派",
                    "请输入对方的用户名或手机号", (str, type) -> {
                String orderSn = item.getOrder_sn();
                zhuaPai(orderSn, str);
            });
            tuiDanDialog.setCanceledOnTouchOutside(false);
            tuiDanDialog.setCancelable(false);
            tuiDanDialog.show();
        });


        // 备注
        holder.setOnClickListener(R.id.iv_beizhu, view -> {
            String orderSn = item.getOrder_sn();
            SelectDataUtils.showBeiZhuDialog(mActivity, new BeiZhuListener() {

                @Override
                public void onBeiZhuBack(String str, String data) {
                    subBeiZhu(item, orderSn, str, data);
                }
            });
        });

        // 地图
        holder.getView(R.id.tv_map).setTag(item);
        holder.setOnClickListener(R.id.tv_map, view -> {
            if (!locationDialog.isVisible()) {
                curentItem = (PaiDanOrder.DataBeanX.OrderItemBean) view.getTag();
                locationDialog.show();
            }
        });

        // 完成

        holder.setOnClickListener(R.id.tv_write, view -> {

            order_type = item.getOrder_type();
            String orderSn = item.getOrder_sn();
            if (orderSn != null && !TextUtils.isEmpty(orderSn)) {
                // 电销订单
                // 商城订单
                TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "完成", "请输入号码", (str, type) -> {
                    if (orderSn != null && !TextUtils.isEmpty(orderSn)) {
                        finishOrder(orderSn, str, order_type);
                    } else {
                        ToastUtils.showShortToast(mContext, "订单号为空");
                    }
                });
                tuiDanDialog.setCanceledOnTouchOutside(false);
                tuiDanDialog.setCancelable(false);
                tuiDanDialog.show();

            } else {
                ToastUtils.showShortToast(mContext, "订单号为空");
            }
        });
        // 打电话

        holder.setOnClickListener(R.id.iv_phone, view -> {

            buyerMobil = item.getBuyer_mobile();
            if (buyerMobil != null && !TextUtils.isEmpty(buyerMobil)) {
                TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "提示", buyerMobil, (str, type) -> {
                    final String orderSn = item.getOrder_sn();
                    App.getApp().getHttpTools().callPhoneData(orderSn, new RequestCallBack() {
                        @Override
                        public void onSuccess(Object s) {
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                        }

                        @Override
                        public void onCancelled(Callback.CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                    // 确认拨打电话
                    mAddPhoneNumItemListener.setPremmsionItemListener(buyerMobil);
                });
                tuiDanDialog.setCanceledOnTouchOutside(false);
                tuiDanDialog.setCancelable(false);
                tuiDanDialog.show();
            } else {
                ToastUtils.showShortToast(mContext, "电话号码为空");
            }
        });
    }

    private void tuiDan(final PaiDanOrder.DataBeanX.OrderItemBean item, final String orderSn, final String str, final int type, final String orderType) {
        dialog.show();
        App.getApp().getHttpTools().tuiDan(orderSn, str, type, orderType, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Gson gson = new Gson();
                    IdInfo idInfo = gson.fromJson(s, IdInfo.class);
                    if (idInfo != null) {
                        if (idInfo.getStatus() == 1) {
                            item.setOrder_money("0425");
                            notifyDataSetChanged();
                        } else if (idInfo.getStatus() == 401) {
                            Boolean sucRef = RefReshToken.refshToken();
                            if (sucRef) {
                                tuiDan(item, orderSn, str, type, orderType);
                            } else {
                                RefReshToken.exitLogin();
                            }
                        } else {
                            ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                        }

                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });
    }

    private void zhuaPai(final String orderSn, final String userName) {

        dialog.show();
        App.getApp().getHttpTools().zhuanPai(orderSn, userName, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Gson gson = new Gson();
                    IdInfo idInfo = gson.fromJson(s, IdInfo.class);
                    if (idInfo != null) {
                        if (idInfo.getStatus() == 1) {
                            ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                            if (mRefOrderListListener != null) {
                                mRefOrderListListener.onRefreshOrder();
                            }
                        } else if (idInfo.getStatus() == 401) {
                            Boolean sucRef = RefReshToken.refshToken();
                            if (sucRef) {
                                zhuaPai(orderSn, userName);
                            } else {
                                RefReshToken.exitLogin();
                            }
                        } else {
                            ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                        }

                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });

    }

    private void finishOrder(final String orderSn,
                             final String phoneNum, final String orderType) {
        dialog.show();
        App.getApp().getHttpTools().finishOrder(orderSn, orderType,
                phoneNum, new RequestCallBack<String>() {

                    @Override
                    public void onSuccess(String result) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        try {
                            Gson gson = new Gson();
                            IdInfo idInfo = gson.fromJson(result, IdInfo.class);
                            if (idInfo != null) {
                                if (idInfo.getStatus() == 401) {
                                    Boolean sucRef = RefReshToken.refshToken();
                                    if (sucRef) {
                                        finishOrder(orderSn, phoneNum, orderType);
                                    } else {
                                        RefReshToken.exitLogin();
                                    }
                                } else {
                                    ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                                }
                            } else {
                                ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        ToastUtils.showShortToast(mActivity, "网络或服务器错误");
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }

                });
    }

    private AddPhoneNumItemListener mAddPhoneNumItemListener;

    public void setItemSelectListener(AddPhoneNumItemListener addPhoneNumItemListener) {
        mAddPhoneNumItemListener = addPhoneNumItemListener;
    }

    private void subBeiZhu(PaiDanOrder.DataBeanX.OrderItemBean item, final String orderSn,
                           final String remark, String data) {
        Log.e("项目异常", orderSn + "------subBeiZhu------" + remark + "---data---" + data);
        dialog.show();
        App.getApp().getHttpTools().beiZhu(orderSn, remark, data, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Gson gson = new Gson();
                    IdInfo idInfo = gson.fromJson(result, IdInfo.class);
                    if (idInfo != null) {
                        if (idInfo.getStatus() == 1) {
                            item.setStatus("0425");
                            item.setRemark(remark);
                            notifyDataSetChanged(); // 更新状态
                        } else if (idInfo.getStatus() == 401) {
                            Boolean sucRef = RefReshToken.refshToken();
                            if (sucRef) {
                                subBeiZhu(item, orderSn, remark, data);
                            } else {
                                RefReshToken.exitLogin();
                            }
                        } else {
                            ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                        }

                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                    Log.e("项目异常", "数据解析异常:" + e.toString());
                    ToastUtils.showShortToast(mActivity, "数据解析异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
                if (dialog != null) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });

    }

}
